package com.googlecode.monitoring.service;

import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.model.Person;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service(value = "emailService")
public class DefaultEmailService implements EmailService {

    Logger log = Logger.getLogger(DefaultEmailService.class);
    private JavaMailSender mailSender;
    private AlertTextService alertTextService;

    @Autowired
    public void setAlertTextService(AlertTextService alertTextService) {
        this.alertTextService = alertTextService;
    }

    @Autowired
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * send email to responsiblePerson if data in DbItemToCheck is outdated
     *
     * @param item  item to check
     * @param commonPersons list of common person
     * @return true if email was sent
     */
    @Override
    public boolean sendAlertEmail(ItemToCheck item) {
        for (Person person : item.getResponsiblePersons()) {
            mailSender.send(alertTextService.buildMessage(person, item));
            log.debug("email was sent for itemId = " + item.getId());
        }
        return true;
    }
}
